<?php

namespace app\data\command;

use think\admin\Command;
use think\admin\Exception;
use think\console\Input;
use think\console\Output;

/**
 * 复利计算
 * Class CalculateInterest
 * @package app\data\command
 */
class CalculateCompoundInterest extends Command
{
    protected function configure()
    {
        $this->setName('xdata:CalculateCompoundInterest');
        $this->setDescription('定时计算当日产生复利');
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        try {
            $start = date('Y-m-d',strtotime('-1 day'));
            $map = [];
            $map[] = ['deleted_status', '=', 0];
            $map[] = ['status', '=', 1];
            $map[] = ['start_at', '<=', $start];
            $map[] = ['end_at', '>', $start];
            $map[] = ['goods_return_rule', '=', 2];

            $count = 0;
            $this->app->log->info("开始计算昨日复利");
            $this->app->db->name('ShopOrder')->where($map)->chunk(50, function ($orders) use($count){

                foreach ($orders as $order){
                    if($this->calculate($order)){
                        $count ++;
                    }
                }
            });
            $this->app->log->info('昨日复利计算完成，共'.$count.'条成功');
        } catch (Exception $exception) {
            throw $exception;
        } catch (\Exception $exception) {
            $this->setQueueError($exception->getMessage());
        }
    }


    /**
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    private function calculate($order): bool
    {
        try{
            $yesterday = date('Y-m-d', strtotime('-1 day'));
            $annualRate = $order['goods_annual_rate']/100;
            $dayRate = $annualRate/365;
            $data = [];
            $orderItem = $this->app->db->name('ShopOrderItem')->where('order_id' , $order['id'])->order('date', 'desc')->find();
            if($orderItem){
                $startAt = date('Y-m-d', strtotime ("+1 day", strtotime($orderItem['date'])));
                $dayNumber = getDayNum($yesterday, $startAt);
                $oldAmount = $orderItem['new_amount'];
            }else{
                $startAt = $order['start_at'];
                $dayNumber = getDayNum($yesterday, $startAt);
                $oldAmount = 0;
            }
            if($orderItem['date'] == $yesterday){
                return true;
            }
            for($i=0;$i<=$dayNumber;$i++){
                $temp = [];
                $temp['goods_id'] = $order['goods_id'];
                $temp['order_id'] = $order['id'];
                //旧复利金额
                $temp['old_amount'] = $oldAmount;
                //新复利金额
                $temp['new_amount'] = sprintf('%.2f' , ($oldAmount+$order['money'])*(1+$dayRate)-$order['money']);
                //当日增长复利金额
                $temp['change_amount'] = sprintf('%.2f' , $temp['new_amount'] - $temp['old_amount']);
                //旧利息本金总额
                $temp['old_total_amount'] = sprintf('%.2f' ,$order['money'] + $temp['old_amount']);
                //新利息本金总额
                $temp['new_total_amount'] = sprintf('%.2f' , $order['money'] + $temp['new_amount']);

                $temp['date'] = date('Y-m-d', strtotime ("$startAt+{$i} day"));
                $oldAmount = sprintf('%.2f' , $temp['old_amount'] + $temp['change_amount']);

                $data[] = $temp;
            }
            $this->app->db->name('ShopOrder')
                ->where('id',$order['id'])
                ->update(
                    [
                        'update_at'=>date('Y-m-d H:i:s'),
                        'current_lxflje'=> $oldAmount,
                    ]
                );
            $this->app->db->name('ShopOrderItem')->insertAll($data);

            $this->app->log->info("订单id{$order['id']}更改完成");

            return true;
        }catch (\Exception $e){
            $this->app->log->info("订单id{$order['id']}更改失败");
            return false;
        }

    }
}